﻿#include "UserRegisterCodec_Register.h"

#include "Mapper_User.h"
#include "RegisterCenter_User.h"
#include "User.h"

#include "qdebug.h"

UserRegisterCodec_Register::UserRegisterCodec_Register()
{
  setObjectName(getClassNameFirstLow<UserRegisterCodec_Register>());
}

UserRegisterCodec_Register::~UserRegisterCodec_Register()
{

}

DataPackage_UserRegisterCodec* UserRegisterCodec_Register::decode(DataPackage_UserRegisterCodec* dataPackage_UserRegisterCodec)
{
  QByteArray data=dataPackage_UserRegisterCodec->getData();
  if(data.size()<4)
    {
      return Q_NULLPTR;
    }
  int index_userName=data.indexOf(userNameFlag)
      ,index_password=data.indexOf(passwordFlag);
  if(-1==index_userName||-1==index_password||index_password<index_userName)
    {
      return Q_NULLPTR;
    }
  QString userName=data.mid(index_userName+1,index_password-index_userName-1);
  QString password=data.mid(index_password+1);
  int user_id;
  if(mapper_User->isVaildUser(userName,password,&user_id))
    {
      if(registerCenter_User->isOnline(user_id))
        {
          return dataPackage_UserRegisterCodec->setData(QByteArray(Registered,1));
        }
      registerCenter_User->userLogin((new class User())->setUserId(user_id)
                                     ,dataPackage_UserRegisterCodec->getTcpIOer());
      logSaver->saveLog("UserRegisterCodec,user "+QString::number(user_id)+" login succeed");
      return dataPackage_UserRegisterCodec->setData(QByteArray(Register,1));//返回注册成功
    }
  else
    {
      logSaver->saveLog("UserRegisterCodec,user login faild");
      return dataPackage_UserRegisterCodec->setData(QByteArray(1,(char)Unregister));//返回注册失败
    }
}

Mapper_User* UserRegisterCodec_Register::getMapper_User()const
{
  return mapper_User;
}

UserRegisterCodec_Register* UserRegisterCodec_Register::setMapper_User(Mapper_User* const mapper_User)
{
  this->mapper_User=mapper_User;
  printInjection(this,mapper_User);
  return this;
}

RegisterCenter_User* UserRegisterCodec_Register::getRegisterCenter_User()const
{
  return registerCenter_User;
}

UserRegisterCodec_Register* UserRegisterCodec_Register::setRegisterCenter_User(RegisterCenter_User* const registerCenter_User)
{
  this->registerCenter_User=registerCenter_User;
  printInjection(this,registerCenter_User);
  return this;
}

void UserRegisterCodec_Register::objectAutoInjection(QHash<QString,QObject*>* objMap)
{
  setMapper_User(getObjFromMap<Mapper_User>(objMap));
  setRegisterCenter_User(getObjFromMap<RegisterCenter_User>(objMap));
}
